<template>
  <div class="form-container section" :data-ap="apk">
    <AiFormSearch
      ref="formRef"
      :id="id"
      :data="list"
      :btns="btns"
      @search="search"
      @select="select"
      @btnCK="btnCK"
      :layout="config.layout"
    ></AiFormSearch>
  </div>
</template>

<script setup>
const formRef = ref();
const props = defineProps({
  id: {
    type: String,
    default: "",
  },
  apk: {
    type: String,
    default: "",
  },
  select: {
    type: Function,
    default: () => {},
  },
  children: {
    type: Array,
    default: () => {
      return [];
    },
  },
  config: {
    type: Object,
    default: () => {
      return {
        layout: "horizontal",
        search: true,
        reset: true,
        children: [],
      };
    },
  },
});

const emit = defineEmits();

const list = ref([]);
const btns = ref([]);

const search = (val) => {
  const comm = props.config;
  formRef.value
    ?.validate()
    .then(() => {
      emit("Form__Search", comm, val);
    })
    .catch((error) => {
      console.log("error", error);
    });
};
const btnCK = () => {
  emit("Form__BtnCK");
};

/**
 * 选择项函数
 * 该函数用于处理当一个项被选择时的逻辑
 * @param {any} index - 被选择的项
 */
const select = (index) => {
  if (props.select) {
    props.select(index);
  }
};

watch(
  () => props.children,
  (val) => {
    list.value =
      val && val.length
        ? val.map((a, i) => {
            a.attrs.index = a.index;
            return a.attrs;
          })
        : [];
    console.log(val, "=====list======");
  },
  { deep: true, immediate: true },
);

if (props.config.search) {
  btns.value.push({
    label: "搜索",
    type: "primary",
    width: "84px",
    key: "search",
  });
}

if (props.config.reset) {
  btns.value.push({
    label: "重置",
    width: "84px",
    key: "reset",
  });
}
</script>
<style lang="scss" scoped></style>
